package com.tg.base.concurrent;

import java.util.concurrent.TimeUnit;

/**
 * 预估主线程sleep 1秒后终止后台线程
 * 结果：该进程永远都不会结束
 * 原因：boolean域的读和写操作都是原子，没有执行同步，后台线程永远不会结束
 * 虚拟机将
 * while(!done)
 * i++;
 * 转变成
 * if(!done)
 * while(true)
 * i++;
 */
public class StopThread {

    private static boolean stopReq;

    private static int stopReqInt;

    public static void main(String[] args) throws InterruptedException {
        main1();
        //如果不采用boolean控制，采用int，则可以同步
//        main2();
    }

    public static void main1() throws InterruptedException {
                Thread backgroundThread = new Thread(() -> {
            int i = 0;
            while (!stopReq) {
                i++;
            }
        });

        backgroundThread.start();

        TimeUnit.SECONDS.sleep(1);
        stopReq = true;
    }

    public static void main2() throws InterruptedException {
        Thread backgroundThread = new Thread(() -> {
            int i = 0;
            while (stopReqInt > 1) {
                i++;
            }
        });

        backgroundThread.start();

        TimeUnit.SECONDS.sleep(5);
        stopReqInt = 2;
    }
}
